package com.hm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hm.reggie.common.CustomException;
import com.hm.reggie.dto.SetmealDto;
import com.hm.reggie.entity.Setmeal;
import com.hm.reggie.entity.SetmealDish;
import com.hm.reggie.mapper.SetmealMapper;
import com.hm.reggie.service.SetMealDishService;
import com.hm.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetMealDishService setMealDishService;

    @Override
    @Transactional
    public void saveSetmealWithDish(SetmealDto setmealDto) {
        //先保存主表Setmeal
        //Setmeal setmeal = new Setmeal();
        //BeanUtils.copyProperties(setmealDto,setmeal);
        //insert进去以后，id就会注入到dto对象的id里面
        this.save(setmealDto);

        //保存子表Setmealdish
        List<SetmealDish> setmealDishes = new ArrayList<>();
        setmealDishes = setmealDto.getSetmealDishes();
        //要把setmeal的id写进子表
        for (SetmealDish setmealDish:setmealDishes){
            setmealDish.setSetmealId(setmealDto.getId());
            log.info(setmealDish.toString());
        }
        setMealDishService.saveBatch(setmealDishes);

    }

    @Override
    @Transactional
    public void removeWithDishByIds(Long[] ids) {
        //先判断套餐的售卖状态
        LambdaQueryWrapper<Setmeal> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(Setmeal::getId,ids);
        queryWrapper1.eq(Setmeal::getStatus,1);
        int count = count(queryWrapper1);
        if (count >0) {
            throw new CustomException("套餐起售中，无法删除！");
        }
        //先删除Setmeal表数据
        boolean b = this.removeByIds(Arrays.asList(ids));
        if (b) {log.info("主表删除成功！！");}
        //在删除Setmealdish表
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        for (Long id:ids){
            queryWrapper.eq(SetmealDish::getSetmealId,id);
            boolean remove = setMealDishService.remove(queryWrapper);
            if (remove) {log.info("子表删除成功！！");}

        }
        //boolean remove = setMealDishService.remove(queryWrapper);

    }

    @Override
    public void updateSetmealStatusByIds(int status,Long[] ids) {
        //把传过来的status写进setmeal
        for (Long id:ids){
            Setmeal setmeal = this.getById(id);
            setmeal.setStatus(status);
            this.updateById(setmeal);
        }
    }



}
